package com.hh.bidding.controller;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.hh.bidding.domain.BidNotice;
import com.hh.bidding.domain.BidTenderInvitation;
import com.hh.bidding.domain.BsOperator;
import com.hh.bidding.service.IBidNoticeService;
import com.hh.bidding.service.IBidTenderInvitationService;
import com.hh.bidding.service.business.BidInvitationServiceBusiness;
import com.hh.bidding.service.business.IBidMailService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 邀请供应商招投标Controller
 *
 * @author ruoyi
 * &#064;date  2025-10-17
 */
@RestController
@RequestMapping("/invitation")
public class BidTenderInvitationController extends BaseController
{
    @Resource
    private IBidNoticeService bidNoticeService;
    @Resource
    private IBidTenderInvitationService bidTenderInvitationService;
    @Resource
    private IBidMailService bidMailService;
    @Resource
    private BidInvitationServiceBusiness bidInvitationServiceBusiness;

    /**
     * 查询邀请供应商招投标列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BidTenderInvitation bidTenderInvitation)
    {
        startPage();
        List<BidTenderInvitation> list = bidTenderInvitationService.selectBidTenderInvitationList(bidTenderInvitation);
        return getDataTable(list);
    }

    /**
     * 导出邀请供应商招投标列表
     */
    @Log(title = "邀请供应商招投标", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BidTenderInvitation bidTenderInvitation)
    {
        List<BidTenderInvitation> list = bidTenderInvitationService.selectBidTenderInvitationList(bidTenderInvitation);
        ExcelUtil<BidTenderInvitation> util = new ExcelUtil<BidTenderInvitation>(BidTenderInvitation.class);
        util.exportExcel(response, list, "邀请供应商招投标数据");
    }

    /**
     * 获取邀请供应商招投标详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bidTenderInvitationService.selectBidTenderInvitationById(id));
    }

    @GetMapping(value = "/invitationByUidSid/{uid}/{sid}")
    public AjaxResult invitationByUidSid(@PathVariable("uid") Long uid, @PathVariable("sid") Long sid)
    {
        BidTenderInvitation bidTenderInvitation = new BidTenderInvitation();
        bidTenderInvitation.setUid(uid);
        bidTenderInvitation.setSid(sid);
        return success(bidTenderInvitationService.selectBidTenderInvitationList(bidTenderInvitation));
    }

    /**
     * 新增邀请供应商招投标
     */
    @Log(title = "邀请供应商招投标", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BidTenderInvitation bidTenderInvitation)
    {
        int rows = 0;
        List<Long> list = bidTenderInvitation.getHids();
        Long sid = bidTenderInvitation.getSid();
        Long uid = bidTenderInvitation.getUid();
        if(list != null && list.size() > 0){
            Map<Long,List<BidTenderInvitation>> invitationMap = new HashMap<>();
            List<BidTenderInvitation> tempInvitationList = bidTenderInvitationService.selectBidTenderInvitationListBySid(sid);
            if(tempInvitationList != null && tempInvitationList.size() > 0){
                Map<Long,List<BidTenderInvitation>> map = tempInvitationList.stream().collect(Collectors.groupingBy(BidTenderInvitation::getUid));
                if(map != null && map.size() > 0){
                    List<BidTenderInvitation> invitationList = map.get(uid);
                    if(invitationList != null && invitationList.size() > 0){
                        invitationMap = invitationList.stream().collect(Collectors.groupingBy(BidTenderInvitation::getHid));
                    }
                }
            }
            //处理新增和删除,然后返回新增成功的
            List<BidTenderInvitation> newSuccessList = bidInvitationServiceBusiness.handlerInvitation(uid,sid,bidTenderInvitation.getsCode(),list);
            Map<Long,BidTenderInvitation> successMap = new HashMap<>();
            if(newSuccessList != null && newSuccessList.size() > 0){
                rows = newSuccessList.size();
                for(BidTenderInvitation tempInvitation : newSuccessList){
                    successMap.put(tempInvitation.getHid(),tempInvitation);
                }
            }else{
                rows = 1;
            }
            //发邮件
            List<BsOperator> operatorsList = bidNoticeService.selectAllBsOperator();
            //发布公告的时候发邮件
            Map<Long,BsOperator> map = new HashMap<>();
            if(operatorsList != null && operatorsList.size() > 0){
                for(BsOperator operator : operatorsList){
                    map.put(operator.getHid(),operator);
                }
            }
            BidNotice bidNotice = bidNoticeService.selectBidNoticeByUid(uid);
            for(Long hid : list){
                try {
                    if(invitationMap != null && invitationMap.get(hid) == null && successMap.get(hid) != null){
                        //不存在
                        BsOperator operator = map.get(hid);
                        if(operator != null){
                            String email = operator.getYwMailbox();
                            String title = bidNotice.getuTitle();
                            if(StringUtils.hasLength(title) && title.contains("公告")){
                                title = title.replace("公告","");
                            }
                            String resultTitle = title + "邀请";
                            boolean emailSuccess = false;
                            try{
                                if(StringUtils.hasLength(email) && StringUtils.hasLength(bidNotice.getFjRemark())){
                                    bidMailService.sendHtmlMail(email,resultTitle,bidNotice.getFjRemark());
                                    emailSuccess = true;
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else{
            //可能需要删除
            if(uid != null && uid > 0){
                rows = bidTenderInvitationService.deleteBidTenderInvitationByUId(uid);
            }
        }
        return toAjax(rows);
    }

    /**
     * 修改邀请供应商招投标
     */
    @Log(title = "邀请供应商招投标", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BidTenderInvitation bidTenderInvitation)
    {
        return toAjax(bidTenderInvitationService.updateBidTenderInvitation(bidTenderInvitation));
    }

    /**
     * 删除邀请供应商招投标
     */
    @Log(title = "邀请供应商招投标", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bidTenderInvitationService.deleteBidTenderInvitationByIds(ids));
    }
}
